package com.xuzm.netty.operator;

import cn.hutool.core.map.BiMap;
import com.xuzm.netty.dto.RunDataDto;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class ServerHandlerOperator {

    //k=地址（ip+端口），v=mmsi
    protected static final BiMap<String, String> ADDR_MMSI_MAP = new BiMap<>(new ConcurrentHashMap<>());
    // 离线的地址（ip+端口）
    protected static final List<String> DOWN_ADDR = Collections.synchronizedList(new ArrayList<>());
    //k=地址（ip+端口）， v=链接对象
    protected static final BiMap<String, RunDataDto> MAP1 = new BiMap<>(new ConcurrentHashMap<>());
    protected static final BiMap<String, RunDataDto> MAP2 = new BiMap<>(new ConcurrentHashMap<>());
    // 转换开关
    public static final AtomicBoolean SWITCH_FLAG = new AtomicBoolean(true);

    /**
     * 获取存储的map
     */
    public static BiMap<String, RunDataDto> getDtoMap(){
        return SWITCH_FLAG.get()? MAP1: MAP2;
    }

    /**
     * 数据储存切换
     * @return 历史数据
     */
    public static synchronized BiMap<String, RunDataDto> switchMap(){
        BiMap<String, RunDataDto> dtoMap = getDtoMap();
        SWITCH_FLAG.getAndSet(!SWITCH_FLAG.get());
        // 清理前一天的数据
        getDtoMap().clear();
        return dtoMap;
    }

    /**
     * 获取客服端的ip+端口
     */
    protected String getClientAddr(ChannelHandlerContext ctx){
        InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        return remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort();
    }

    protected String getClientIp(ChannelHandlerContext ctx){
        InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        return remoteAddress.getAddress().getHostAddress();
    }

    protected int getClientPort(ChannelHandlerContext ctx){
        InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        return remoteAddress.getPort();
    }



    public void exec(ChannelHandlerContext ctx){
        exec(ctx, null);
    }
    public abstract void exec(ChannelHandlerContext ctx, Object obj);
}
